package exam.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * @author jzh
 * @创建时间 2017年6月9日下午6:38:32 类说明：
 */
public class JDBCUtil {
	// 获得数据库连接的Connection
	public static Connection getConnection() {
		// 实例化Properties对象
		Properties props = new Properties();
		Connection conn = null;
		try {
			// 把配置文件load进内存
			props.load(new FileReader(new File("E:/workspace/jzh-exam/src/main/resources/jdbc.properties")));
			// 从配置文件中读取值
			String driver = props.getProperty("jdbc.driver");
			String url = props.getProperty("jdbc.url");
			String user = props.getProperty("jdbc.user");
			String password = props.getProperty("jdbc.password");
			// 加载驱动
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 关闭数据库连接的资源
	public static void closeSource(Connection conn, PreparedStatement ps) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != ps) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void closeSource(Connection conn, Statement stat) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != stat) {
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void closeSource(Connection conn, PreparedStatement ps, ResultSet rs) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != ps) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 把json对象返回到前台
	public static void printJson(HttpServletResponse response, Map<String, Object> map) {
		// Map<String ,String> addMap=new HashMap<String ,String>();

		Gson json = new Gson();
		String jsonString = json.toJson(map);
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		pw.write(jsonString);
		pw.flush();
		pw.close();
	}
}
